package com.be.beadmin.design.controller;

import com.alibaba.excel.EasyExcel;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.design.dto.input.ProductDrawingInfoDto;
import com.be.beadmin.design.dto.input.StandFileInfoDto;
import com.be.beadmin.design.dto.output.ProductDrawingInfoEx;
import com.be.beadmin.design.entity.ProductDrawingInfo;
import com.be.beadmin.design.mapper.ProductDrawingInfoMapper;
import com.be.beadmin.design.repository.ProductDrawingInfoRepository;
import com.be.beadmin.design.service.ProductDrawingInfoService;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
* @author zmy
* @date 2023-02-16
**/
@Api(tags = {"设计管理-图纸"})
@RestController
public class ProductDrawingInfoController {

    @Autowired
    private  ProductDrawingInfoService productDrawingInfoService;

    @Autowired
    private ProductDrawingInfoRepository productDrawingInfoRepository;

    @Autowired
    private ProductDrawingInfoMapper productDrawingInfoMapper;
    @Autowired
    private MinioService minioService;
    public String drawingBucketName = "drawing";

    MinioUtil minioUtil = new MinioUtil();

    private String code="nonStandardDrawingCode";

    @PostMapping(value = "/design/getProductDrawingInfoByPage")
    public ResultModel getProductDrawingInfoByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(productDrawingInfoService.getProductDrawingInfoByPage(pageEntity)) ;
    }

    @PostMapping(value = "/design/getProductDrawing")
    public ResultModel getProductDrawing(@RequestBody List<String> batchProductIds)  {
        return ResultModel.success(productDrawingInfoService.getProductDrawing(batchProductIds)) ;
    }
    @ApiOperation("获取某一个柜体的图纸")
    @PostMapping(value = "/design/getDrawingByBatchProductId")
    public ResultModel getProductBomOverviewByBatchProductId(@RequestBody PageEntity pageEntity,
                                                             @ApiParam(value = "批次柜体id",required = true) @RequestParam String batchProductId,
                                                             HttpServletRequest request) {
        try {
            productDrawingInfoService.getDrawingByBatchProductId(request,pageEntity,batchProductId);
        }catch (RuntimeException e){
            return ResultModel.error(110, e.getMessage());
        }
        return ResultModel.success();
    }

    @PostMapping("/design/addProductDrawingInfo")
    public ResultModel addProductDrawingInfo(@RequestBody ProductDrawingInfoDto productDrawingInfoDto){
        productDrawingInfoService.addProductDrawingInfo(productDrawingInfoDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/design/delProductDrawingInfo")
    public ResultModel delProductDrawingInfo(@RequestBody ProductDrawingInfoDto productDrawingInfoDto){
        productDrawingInfoService.delProductDrawingInfo(productDrawingInfoDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }


    @PostMapping("/design/updateProductDrawingInfo")
    public ResultModel updateProductDrawingInfo(@RequestBody ProductDrawingInfoDto productDrawingInfoDto){
        productDrawingInfoService.updateProductDrawingInfo(productDrawingInfoDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/design/exportProductDrawingInfo")
    public void exportProductDrawingInfo(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<ProductDrawingInfoEx> productDrawingInfoPage = productDrawingInfoService.getProductDrawingInfoByPage(pageEntity);
        List<ProductDrawingInfoEx> productDrawingInfoExes = productDrawingInfoPage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("ProductDrawingInfo接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ProductDrawingInfoEx.class).sheet("sheet1").doWrite(productDrawingInfoExes);
    }

    @ApiOperation("上传图纸")
    @PostMapping("/design/uploadDrawing")
    public ResultModel uploadDrawing(@ApiParam(value = "产品/柜体编号") @RequestParam String productCode,
                                     @ApiParam(value = "图纸") @RequestParam(value = "file") MultipartFile[] multipartFiles,
                                     @ApiParam(value = "文件类别") @RequestParam String category,
                                     @ApiParam(value = "图纸描述",required = false) @RequestParam(required = false) String drawingSpec) throws Exception {

        productDrawingInfoService.uploadDrawing(productCode,multipartFiles,drawingSpec,drawingBucketName,category);
        return ResultModel.success("成功上传图纸！");
    }

//    @ApiOperation("更新图纸")
//    @PostMapping("/design/updateProductDrawingInfo2")
//    public ResultModel updateProductDrawingInfo2(@ApiParam(value = "图纸id") @RequestParam String drawingId,
//                                                @ApiParam(value = "图纸") @RequestParam(value = "file",required = false) MultipartFile multipartFile,
//                                                 @ApiParam(value = "图纸描述",required = false) @RequestParam(required = false) String drawingSpec,
//                                                 @ApiParam(value = "柜体Code") @RequestParam String productCode) throws Exception {
//
//        productDrawingInfoService.updateProductDrawingInfo2(drawingId,multipartFile,drawingSpec,drawingBucketName,productCode);
//        return ResultModel.success("成功更新图纸！");
//    }

    @ApiOperation("下载图纸")
    @GetMapping("/design/downloadProductDrawingInfo")
    public void downloadProductDrawingInfo(@ApiParam(value = "id") @RequestParam String id,
                                                  HttpServletResponse response) throws Exception {

        //productDrawingInfoService.downloadProductDrawingInfo(id,drawingBucketName,response);
        try {

            //InputStream inputStream = fileInfoService.download(bucketName, id, response);
            ProductDrawingInfo productDrawingInfo= productDrawingInfoRepository.findProductDrawingInfoByIdAndDelete(id, 0);
            String drawingName = productDrawingInfo.getDrawingName();
            //System.out.println(drawingName);
            InputStream inputStream = minioService.downloadOne(drawingBucketName, productDrawingInfo.getDrawingSequence());
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-disposition", "attachment;filename= "+drawingName);
            //System.out.println(drawingName.substring(drawingName.indexOf("-")-1));
            response.addHeader("Content-Type", "text/plain;charset=utf-8");
            //response.addHeader("Content-Length",String.valueOf(inputStream.available()));
            response.addHeader("Pragma","No-cache");
            response.addHeader("Cache-Control","No-cache");
            ServletOutputStream os = response.getOutputStream();

            ByteStreams.copy(inputStream, os);
            os.flush();
            //return  ResultModel.success("下载成功");
        } catch (Exception e) {
            //return ResultModel.error(99,"文件读取异常");
        }

    }

    @ApiOperation("删除图纸")
    @PostMapping("/design/deleteProductDrawingInfo")
    public ResultModel deleteProductDrawingInfo(@ApiParam(value = "drawingId") @RequestParam String drawingId) throws Exception {

        productDrawingInfoService.deleteProductDrawingInfo(drawingId,drawingBucketName);
        return ResultModel.success("成功删除图纸！");
    }

    @ApiOperation("停用")
    @PostMapping("/design/stopIsActive")
    public ResultModel stopIsActive(@ApiParam(value = "启用图纸的id") @RequestParam("id") String id) {

        productDrawingInfoService.stopIsActive(id);
        return ResultModel.success("成功停用！");
    }
    @ApiOperation("启用")
    @PostMapping("/design/onIsActive")
    public ResultModel onIsActive(@ApiParam(value = "启用图纸的id") @RequestParam("id")  String id,
                                       @ApiParam(value = "产品/柜体编号") @RequestParam String productCode,
                                       @ApiParam(value = "文件类别") @RequestParam String category) {

        productDrawingInfoService.updateIsActive2(id,productCode,category);
        return ResultModel.success("成功启用！");
    }

//    @ApiOperation("变更图纸")
//    @PostMapping("/design/changeDrawing")
//    public ResultModel changeDrawing(@ApiParam(value = "产品/柜体编号") @RequestParam String productCode,
//                                     @ApiParam(value = "图纸") @RequestParam(value = "file") MultipartFile multipartFile,
//                                     @ApiParam(value = "文件类别") @RequestParam String category,
//                                     @ApiParam(value = "图纸描述",required = false) @RequestParam(required = false) String drawingSpec) throws Exception {
//
//        productDrawingInfoService.changeDrawing(productCode,multipartFile,drawingSpec,drawingBucketName,category);
//        return ResultModel.success("成功上传图纸！");
//    }
    @ApiOperation("获取最新的pdf、图片的预览url")
    @PostMapping ("/design/getDrawingInfoPreviewUrl")
    public ResultModel getDrawingInfoPreviewUrl(@RequestParam (value = "drawingId") String drawingId) throws Exception {
        ProductDrawingInfo productDrawingInfo = productDrawingInfoRepository.findProductDrawingInfoById(drawingId);
        String previewUrl = minioUtil.getPreviewFileUrl(drawingBucketName,productDrawingInfo.getDrawingSequence());
        productDrawingInfo.setDrawingUrl(previewUrl);
        productDrawingInfoRepository.save(productDrawingInfo);
        ResultModel<String> res = new ResultModel<>();
        res.setCode(200);
        res.setMessage(previewUrl);
        return res;
    }
}